﻿using BLL;
using Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using SQLHelper;
using 后整理管理系统.数据分析;
using 纺织贸易管理系统;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.新增窗体;
using 后整理管理系统.其他窗体;
using 后整理管理系统.入库管理;
using 后整理管理系统.自定义类;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 客供底布入库列表 : Form
    {
        public 客供底布入库列表()
        {
            InitializeComponent();
            uiDatePicker2.Value = DateTime.Now.Date.AddDays(1).AddSeconds(-1);
            uiDatePicker1.Value = uiDatePicker2.Value.AddDays(-QueryTime.间隔);
            CreateGrid.Create(this.Name, gridView1);
           // gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = AccessBLL.CheckAccess("上卷米数");
            gridView1.Columns["rq"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
            //gridView1.Columns["chengpingmishu"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom ;
            gridView1.Columns["chengpingmishu"].DisplayFormat.FormatString = "F0";
            gridView1.Columns["chengpingjuanshu"].DisplayFormat.FormatString = "N0";
            gridView1.OptionsCustomization.AllowSort = true;
            query();
        }

        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 来货入库单() { Useful=FormUseful.新增 }) ;
        }
        private void query()
        {
            this.ShowWaitForm("正在查询，请等待.............");
            uiDatePicker2.Value = uiDatePicker2.Value.Date.AddDays (1).AddSeconds (-1);
            var dt=Connect.CreatConnect ().Query ($"select * from danjutable,danjumingxitable where danjutable.rq between '{ uiDatePicker1.Value.Date }' and '{uiDatePicker2.Value }' and danjutable.ksmc like '%{txtkehu.Text}%' " +
                    $"and danjumingxitable.pingming like '%{txtpingming.Text.Replace("'", "''") }%' " +
                    $"and danjumingxitable.ganghao like '%{txtganghao .Text.Replace("'", "''") }%' " +
                    $"and danjumingxitable.yanse like '%{txtyanse.Text.Replace("'", "''") }%' " +
                      //$"and danjutable.djlx='{DanjuLeiXing.入库单  }' " +
                      $"and danjumingxitable.danhao like '%SC%' " +
                    $"and danjutable.dh=danjumingxitable.danhao  order by danjutable.id desc");
            gridControl1.DataSource = dt;
            this.HideWaitForm();
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            query();
        }

        private void 来货入库_Load(object sender, EventArgs e)
        {

        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString ();
                var mingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danhao);
                if(Connect.dbcontext.Queryable<StockTable>().Where(x=>x.RKDH==danhao&&!string.IsNullOrWhiteSpace(x.LiuzhuanCard )).Count()>0)
                {
                    if(Tools.ShowMessageBox.ShowAskBox("该入库单号存在开卡记录！\r\n是否继续修改")==DialogResult.No )
                    {
                        return;
                    }
                }
                if(mingxis.Where (x=>x.toupimishu >0).ToList ().Count >=1)
                {
                    if (Sunny.UI.UIMessageBox.ShowAsk("该入库单已经存在发货记录！\r\n是否继续修改"))
                    {
                        MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.修改, danju = DanjuTableService.GetOneDanjuTable(x => x.dh == danhao) });
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.修改, danju = DanjuTableService.GetOneDanjuTable (x=>x.dh==danhao ) });
                }
               
            }
            else
            {
                Sunny.UI.UIMessageBox.ShowError("没有任何内容被选中!");
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
            if (StockTableService.GetStockTablelst(x => x.RKDH == danhao && x.LiuzhuanCard != string.Empty).Count > 0)
            {
                Sunny.UI.UIMessageBox.ShowError("该单据已经开具流转卡！\r\n不能删除!\r\n请先删除对应的流转卡");
                return;
            }
            if (Sunny.UI.UIMessageBox.ShowAsk($"您确定要删除{danhao  }该来货登记单吗?") == true)
            {
                var juanhaos = Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.ReceiptNo == danhao).ToList();
                if(juanhaos.Count >0)
                {
                    if (Sunny.UI.UIMessageBox.ShowAsk($"该来货入库单号{danhao }已经存在打卷记录！\r\n删除该入库单号将会清空该入库单号对应的打卷记录\r\n是否继续删除？") == false)
                    {
                        return;
                    }
                }
                try
                {
                    Connect.dbcontext.BeginTran();
                    生产入库单BLL.Delete(danhao );
                    Connect.dbcontext.Insertable(new DeleteLog() { date = DateTime.Now, Log = $"删除生产入库单{danhao }", useID = Tools.CurrentUser.user.YHBH }).ExecuteCommand ();
                    Connect.dbcontext.CommitTran();
                    AlterDlg.Show("删除成功");
                    query();
                }
                catch (Exception ex)
                {
                    Connect.dbcontext.RollbackTran();
                    Sunny.UI.UIMessageBox.ShowError("删除失败！原因是：" + ex.Message);
                }
            }
        }

        private void 导出到EXCELToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl1, "生产入库清单");
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = null, dt = gridControl1.DataSource as DataTable };
            fm.ShowDialog();
            //gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = AccessBLL.CheckAccess("上卷米数");
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }
        private void 入库日报表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 进仓日报表());
        }

        private void 入库月报表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 进仓月报表());
        }

        private void 复制单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridControl1.Focus();
            SendKeys.Send("^c");
        }

        private void txtganghao_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                query();
            }
        }

        private void 出库信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
                var ganghao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ganghao").ToString();
                var yanse = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "yanse").ToString();
                var xiaoshoumingxi = danjumingxitableService.Getdanjumingxitablelst(x => x.rkdh == danhao&&x.yanse==yanse&&x.ganghao==ganghao);
                if(xiaoshoumingxi.Count >0)
                {
                    var saledanhao = xiaoshoumingxi[0];
                    new 出库信息() { Danhao = danhao, LotNo = xiaoshoumingxi[0].ganghao }.ShowDialog();
                }
            }
            else
            {
                Sunny.UI.UIMessageBox.ShowError("没有任何内容被选中!");
            }
        }

        private void 查看入库细码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
               var FineCodeTable = new DataTable();
                var detaicodelist = Connect.CreatConnect().Query<WarehousingDetailCode>(x => x.DocNum == danhao);
                foreach (var col in detaicodelist.Select(x => x.LotNum).Distinct())
                {
                    int rowindex = 0;
                    FineCodeTable.Columns.Add(col);
                    foreach (var d in detaicodelist.Where(x => x.LotNum == col).ToList())
                    {
                        if (rowindex == FineCodeTable.Rows.Count)
                        {
                            FineCodeTable.Rows.Add();
                        }
                        FineCodeTable.Rows[rowindex][col] = d.Length;
                        rowindex++;
                    }
                }
                var fm = new 输入来货细码()
                {
                    useful = FormUseful.修改,
                    dt = FineCodeTable,
                    mingxilist = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danhao)
                };
                fm.ShowDialog();
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                var ID1 = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID1").ToString();
                //修改上卷米数
                switch (gridView1.FocusedColumn.FieldName)
                {
                    case "UpRolledNum":
                        if (AccessBLL.CheckAccess("上卷米数"))
                        {

                            Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.UpRolledNum == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "UpRolledNum")).ExecuteCommand();
                        }
                        else
                        {
                            ShowMessageBox.ShowErrorBox("您没有权限修改上卷米数");
                            gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                    case "beizhu":
                        Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.beizhu == (string)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "beizhu")).ExecuteCommand();
                        break;
                    case "ExitsNum":
                        if (AccessBLL.CheckAccess("修改退仓米数"))
                        {
                            var d=Connect.dbcontext.Queryable<danjumingxitable>().First (x=>x.ID==ID1.ToInt(0));
                            if(d!=null)
                            {
                                d.ExitsNum = (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ExitsNum");
                                d.InventoryQuantity -= d.ExitsNum;
                                销售发货单BLL.CalculateShrinkage(d);
                                Connect.dbcontext.Updateable(d).ExecuteCommand();
                            }
                            //Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.ExitsNum == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ExitsNum")).ExecuteCommand();
                        }
                        else
                        {
                            ShowMessageBox.ShowErrorBox("您没有权限修改退仓米数");
                            gridView1.Columns["ExitsNum"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                    case "ExitsRoll":
                        if (AccessBLL.CheckAccess("修改退仓卷数"))
                        {

                            Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.ExitsRoll == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ExitsRoll")).ExecuteCommand();
                        }
                        else
                        {
                            ShowMessageBox.ShowErrorBox("您没有权限修改退仓卷数");
                            gridView1.Columns["ExitsRoll"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                }
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox(ex.Message);
            }

        }

        private void 生成出库单ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            { 
                if(gridView1.GetSelectedRows().Length ==0)
                {
                    Tools.ShowMessageBox.ShowErrorBox("没有任何布料被选中！\r\n生成失败");
                    return;
                }
                var stocks = new List<StockTable>();
                foreach (DataRow  r in SelectHelper.GetSelect (gridView1).Rows )
                {
                    var mingxi = danjumingxitableService.GetOnedanjumingxitable(x => x.ID == (int)r["ID1"]);                   
                    var stock = StockTableService.GetOneStockTable(x => x.RKDH == mingxi.danhao && x.YS == mingxi.yanse && x.GH == mingxi.ganghao && x.PM == mingxi.pingming);
                    if(string.IsNullOrWhiteSpace(stock.PM))
                    {
                        //已经出库的信息不能再次出库
                        Tools.ShowMessageBox.ShowErrorBox("生成发货单的时候检查到库存信息已经没有的布料！\r\n缸号是"+stock.GH +"\r\n生成失败");
                        return;
                    }
                    stocks.Add(stock);
                }
                ///不同客户不允许开单
                if(stocks.Select(x=>x.CustomName).Distinct().Count ()>1)
                {
                    Tools.ShowMessageBox.ShowErrorBox("所选布料归属为两个或两个以上客户！\r\n生成失败");
                    return;
                }
                MainForm.mainform.AddMidForm(new 销售发货单() { stockTables = stocks,useful=FormUseful.新增  });
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("创建发货单的时候发送了错误:"+ex.Message);
            }
        }

        private void 查看开卡信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var mingxi = Connect.dbcontext.Queryable<danjumingxitable>().First(x => x.ID== (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID1"));
                if (mingxi != null)
                {
                    new 查看开卡信息() { LotNo = mingxi.ganghao, DocNum = mingxi.danhao }.ShowDialog();
                }
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("查看开卡信息的时候的发生了错误:" + ex.Message);

            }
        }

        private void 流转卡ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
                var danju = Connect.dbcontext.Queryable<DanjuTable>().First(x => x.dh == danhao);
                if (danju != null)
                {
                    MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = Connect.dbcontext.Queryable<danjumingxitable>().Where(x => x.danhao == danhao).ToList(), Useful = FormUseful.复制, danju = new DanjuTable() { ksmc = danju.ksmc, ksbh = danju.ksbh, ckmc = danju.ckmc , bz = danju.bz , jiagongleixing = danju.jiagongleixing } });
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox("下推流转卡的时候发生了错误：" + ex.Message);
            }
         }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
                MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.查看, danju = DanjuTableService.GetOneDanjuTable(x => x.dh == danhao) });
            }
        }
    }
}
